/**
 * 
 */
package com.hexacta.hrs.domain.feedback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

import org.hibernate.Hibernate;

/**
 * Blob ByteArray Utils.
 * 
 * @author mperezvega
 * @date Mar 9, 2009
 */
public final class BlobByteArrayUtils {

    /**
     * Constructor
     * 
     */
    private BlobByteArrayUtils() {
    }

    public static Blob createBlob(final byte[] bytes) {
        return Hibernate.createBlob(bytes);
    }

    public static byte[] toByteArray(final Blob blob) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            return toByteArrayImpl(blob, byteArrayOutputStream);
        } catch (SQLException e) {
            throw new RuntimeException("Not implemented yet.");
        } catch (IOException e) {
            throw new RuntimeException("Not implemented yet.");
        }
    }

    private static byte[] toByteArrayImpl(final Blob blob, final ByteArrayOutputStream byteArrayOutputStream)
            throws SQLException, IOException {
        Long length = blob.length();
        byte[] buffer = new byte[length.intValue()];
        int dataSize;
        InputStream is = blob.getBinaryStream();
        try {
            while ((dataSize = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, dataSize);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return byteArrayOutputStream.toByteArray();
    }

}
